package impl

import (
	"fmt"
	"github.com/RaymondCode/simple-demo/entity/po"
	"github.com/RaymondCode/simple-demo/repository"
	"gorm.io/gorm"
	"sync"
)

type Relation struct {
}

// Insert 插入一条关注关系
func (r Relation) Insert(relation *po.Relation, tx *gorm.DB, isTx bool) error {
	var db1 *gorm.DB
	if isTx {
		db1 = tx
	} else {
		db1 = db
	}
	return db1.Select([]string{"follow_id", "follower_id"}).Create(relation).Error
}

// DeleteByCondition 条件删除关系
func (r Relation) DeleteByCondition(relation *po.Relation, tx *gorm.DB, isTx bool) error {
	var db1 *gorm.DB
	if isTx {
		db1 = tx
	} else {
		db1 = db
	}
	if relation.FollowId != 0 {
		db1 = db1.Where("follow_id = ?", relation.FollowId)
	}
	if relation.FollowerId != 0 {
		db1 = db1.Where("follower_id = ?", relation.FollowerId)
	}
	return db1.Delete(&po.Relation{}).Error
}

// QueryByCondition 条件查询关系
func (r Relation) QueryByCondition(relation *po.Relation) (*[]po.Relation, error) {
	db1 := db.Model(&po.Relation{}).Table("relation")
	if relation.FollowId != 0 {
		db1 = db1.Where("follow_id = ?", relation.FollowId)
	}
	if relation.FollowerId != 0 {
		db1 = db1.Where("follower_id = ?", relation.FollowerId)
	}
	var relations []po.Relation
	err := db1.Find(&relations).Error
	if err != nil {
		return nil, err
	}
	return &relations, nil
}

// QueryFollowIdByFansId 查询关注列表
func (r Relation) QueryFollowIdByFansId(fansId int) ([]int, error) {
	db1 := db.Model(&po.Relation{})
	var userIds []int
	var relations []po.Relation
	db1 = db1.Where("follower_id = ?", fansId)
	if err := db1.Select("follow_id").Find(&relations).Error; err != nil {
		return nil, err
	}
	for _, relation := range relations {
		userIds = append(userIds, relation.FollowId)
	}
	fmt.Println("------", userIds)
	return userIds, nil
}

// QueryFansIdByFollowId 查询粉丝列表
func (r Relation) QueryFansIdByFollowId(followId int) ([]int, error) {
	db1 := db.Model(&po.Relation{})
	var userIds []int
	var relations []po.Relation
	db1 = db1.Where("follow_id = ?", followId)
	if err := db1.Select("follower_id").Find(&relations).Error; err != nil {
		return nil, err
	}
	for _, relation := range relations {
		userIds = append(userIds, relation.FollowerId)
	}
	return userIds, nil
}

var (
	relation     repository.Relation
	relationOnce sync.Once
)

func NewRelationDaoInstance() repository.Relation {
	relationOnce.Do(func() {
		relation = Relation{}
	})
	return relation
}
